package top.dreamcenter.rss.rsssolverweb.util;

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.springframework.stereotype.Component;
import top.dreamcenter.rss.rsssolverprotocal.SpiderTemplate;
import top.dreamcenter.rss.rsssolverweb.enums.BrowserEnum;
import top.dreamcenter.rss.rsssolverweb.exception.RssRuntimeException;
import top.dreamcenter.rss.rsssolverweb.properties.SystemProperties;

import java.io.File;

/**
 *
 */
@Component
public class SpiderHelperFactory {


    private final BrowserEnum browser;
    private final String rootPath;

    public SpiderHelperFactory(SystemProperties systemProperties) {
        browser = systemProperties.getBrowser();
        rootPath = systemProperties.getRssRootPath();

        // 生成根目录
        File root = new File(rootPath);
        if (!root.exists()) root.mkdirs();

        // 配置驱动
        String driverPath = systemProperties.getDriverPath();
        File file = new File(driverPath);
        if (!file.exists()) throw new RssRuntimeException(driverPath + " driver not found!");
        System.setProperty("webdriver." + browser.getType() + ".driver", driverPath);
    }

    public SpiderHelper creator(SpiderTemplate spiderTemplate) {
        switch (browser) {
            case CHROME: {
                //访问限制处理
                ChromeOptions options=new ChromeOptions();
                options.addArguments("--remote-allow-origins=*");

                // 无头模式要设置user-agent，否则会被识别到
                options.addArguments("--headless");
                options.addArguments("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36");

                return new SpiderHelper(new ChromeDriver(options), spiderTemplate, rootPath);
            }
            case  EDGE: {
                //访问限制处理
                EdgeOptions options=new EdgeOptions();
                options.addArguments("--remote-allow-origins=*");

                // 无头模式要设置user-agent，否则会被识别到
                options.addArguments("--headless");
                options.addArguments("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36");

                return new SpiderHelper(new EdgeDriver(options), spiderTemplate, rootPath);
            }
            default: {
                throw new RuntimeException(browser.getType() + " Not realized on current project version");
            }
        }
    }

}
